package com.wang.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Classname CustomerJackSon
 * @Description TODO
 * @Date 2024/5/17 9:31
 * @Created by pc
 */
@Slf4j
@JsonComponent //表示可以将当前的组件注册到jackson中
public class CustomerJackSon {
    public static class MySerializer extends JsonSerializer<Double>{
        private DecimalFormat df = new DecimalFormat("##.00");

        // 序列化方法
        @Override
        public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(df.format(value));
        }
    }

    public static  class MyDeserializer extends JsonDeserializer<Date>{
        private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        @Override
        public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            Date date = null;
            try {
                date = df.parse(p.getText());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        }
    }
}
